package me.zxc.crawler.lyrics;

import me.zxc.utils.ExportUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;

/**
 * 获取utamap的歌词
 * https://www.utamap.com/
 *
 * @author gbandszxc
 */
public class UtaMapParser {

    /**
     * 歌曲id（url里可以看到）
     * eg：https://www.utamap.com/showkasi.php?surl=k-170118-131
     */
    public static final String MUSIC_ID = "k-170118-131";

    /**
     * 歌词页面路径
     */
    public static final String DEST_URL = "https://www.utamap.com/showtop.php?surl=${id}";

    public static void main(String[] args) throws IOException {
        long start = System.currentTimeMillis();
        Document document = null;
        try {
            document = Jsoup.connect(DEST_URL.replace("${id}", MUSIC_ID)).get();
        } catch (IOException e) {
            System.out.println("网络异常，请重试！");
        }
        // 歌曲名
        Elements titleClass = document.getElementsByClass("kasi1");
        String musicName = titleClass.get(0).html();
        // 歌词
        Elements lyricClass = document.getElementsByClass("noprint kasi_honbun");
        if (!lyricClass.isEmpty()) {
            String lyric = lyricClass.get(0).html();
            // 前端换行替换为普通换行
            lyric = lyric.replace("<br>", "\n");
            // 去除结尾注释
            lyric = lyric.replace("<!-- 歌詞 end -->", "");
            // 保存为文本
            String savePath = new File("saved").getCanonicalPath();
            ExportUtil.createPlaintext(lyric, savePath, musicName);
            long end = System.currentTimeMillis();
            long time = end - start;
            System.out.println("【成功】歌词保存完毕！用时" + time + "ms");
            return;
        }
        System.out.println("【失败】当前页面未找到歌词！");
    }

}
